<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>在线编辑Markdown</title>
    <base href="../../.." />
    <link rel="stylesheet" href="./css/style.css" />
    <link rel="stylesheet" href="./css/editormd.css" />
    <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />
</head>
<body style="background:#C7EDCC;">
<div id="layout">
    <header>
        <!--                <h1 align="center"><input type="text" th:value="${title}"></h1>-->
    </header>
    <!--在外层定义一个form，用来取值和提交表单-->
    <form name="mdEditorForm">
        <div id="test-editormd">
            <!--该区域内容为文字内容，非html内容-->
            <textarea name="content" id="content" style="display:none;" th:text="${content}"></textarea>
        </div>
    </form>
</div>
<script src="./js/jquery.min.js"></script>
<script src="./js/editormd.min.js"></script>
<script type="text/javascript">
    var testEditor;
    (function($) {
        $.alerts = {
            alert: function(title, message, callback) {
                if( title == null ) title = 'Alert';
                $.alerts._show(title, message, null, 'alert', function(result) {
                    if( callback ) callback(result);
                });
            },

            confirm: function(title, message, callback) {
                if( title == null ) title = 'Confirm';
                $.alerts._show(title, message, null, 'confirm', function(result) {
                    if( callback ) callback(result);
                });
            },
            _show: function(title, msg, value, type, callback) {

                var _html = "";

                _html += '<div id="mb_box"></div><div id="mb_con"><span id="mb_tit">' + title + '</span>';
                _html += '<div id="mb_msg">' + msg + '</div><div id="mb_btnbox">';
                if (type == "alert") {
                    _html += '<input id="mb_btn_ok" type="button" value="确定" />';
                }
                if (type == "confirm") {
                    _html += '<input id="mb_btn_ok" type="button" value="确定" />';
                    // _html += '<input id="mb_btn_no" type="button" value="取消" />';
                }
                _html += '</div></div>';

                //必须先将_html添加到body，再设置Css样式
                $("body").append(_html); GenerateCss();

                switch( type ) {
                    case 'alert':

                        $("#mb_btn_ok").click( function() {
                            $.alerts._hide();
                            callback(true);
                        });
                        $("#mb_btn_ok").focus().keypress( function(e) {
                            if( e.keyCode == 13 || e.keyCode == 27 ) $("#mb_btn_ok").trigger('click');
                        });
                        break;
                    case 'confirm':

                        $("#mb_btn_ok").click( function() {
                            $.alerts._hide();
                            if( callback ) callback(true);
                        });
                        $("#mb_btn_no").click( function() {
                            $.alerts._hide();
                            if( callback ) callback(false);
                        });
                        $("#mb_btn_no").focus();
                        $("#mb_btn_ok, #mb_btn_no").keypress( function(e) {
                            if( e.keyCode == 13 ) $("#mb_btn_ok").trigger('click');
                            if( e.keyCode == 27 ) $("#mb_btn_no").trigger('click');
                        });
                        break;
                }
            },
            _hide: function() {
                $("#mb_box,#mb_con").remove();
            }
        }
        // Shortuct functions
        zdalert = function(title, message, callback) {
            $.alerts.alert(title, message, callback);
        }
        zdconfirm = function(title, message, callback) {
            $.alerts.confirm(title, message, callback);
        };
        //生成Css
        var GenerateCss = function () {

            $("#mb_box").css({ width: '100%', height: '100%', zIndex: '99999', position: 'fixed',
                filter: 'Alpha(opacity=60)', backgroundColor: 'black', top: '0', left: '0', opacity: '0.6'
            });

            $("#mb_con").css({ zIndex: '999999', width: '20%', position: 'fixed',
                backgroundColor: 'White', borderRadius: '15px'
            });

            $("#mb_tit").css({ display: 'block', fontSize: '14px', color: '#444', padding: '10px 15px',
                backgroundColor: '#DDD', borderRadius: '15px 15px 0 0',
                borderBottom: '3px solid #009BFE', fontWeight: 'bold'
            });

            $("#mb_msg").css({ padding: '20px', lineHeight: '20px',
                borderBottom: '1px dashed #DDD', fontSize: '13px'
            });

            $("#mb_ico").css({ display: 'block', position: 'absolute', right: '10px', top: '9px',
                border: '1px solid Gray', width: '18px', height: '18px', textAlign: 'center',
                lineHeight: '16px', cursor: 'pointer', borderRadius: '12px', fontFamily: '微软雅黑'
            });

            $("#mb_btnbox").css({ margin: '15px 0 10px 0', textAlign: 'center' });
            $("#mb_btn_ok,#mb_btn_no").css({ width: '85px', height: '30px', color: 'white', border: 'none' });
            $("#mb_btn_ok").css({ backgroundColor: '#168bbb' });
            $("#mb_btn_no").css({ backgroundColor: 'gray', marginLeft: '20px' });

            //右上角关闭按钮hover样式
            $("#mb_ico").hover(function () {
                $(this).css({ backgroundColor: 'Red', color: 'White' });
            }, function () {
                $(this).css({ backgroundColor: '#DDD', color: 'black' });
            });

            var _widht = document.documentElement.clientWidth; //屏幕宽
            var _height = document.documentElement.clientHeight; //屏幕高

            var boxWidth = $("#mb_con").width();
            var boxHeight = $("#mb_con").height();
            //让提示框居中
            $("#mb_con").css({ top: (_height - boxHeight) / 2 + "px", left: (_widht - boxWidth) / 2 + "px" });
        }
    })(jQuery);

    $(function() {
        testEditor = editormd("test-editormd", {
            width   : "90%",
            height  : 640,
            syncScrolling : "single",
            path    : "./lib/",
            /**下述为新增，上面一行记得加逗号结束*/
            /*指定需要显示的功能按钮*/
            toolbarIcons : function() {
                return ["undo","redo","|","bold","del","italic","quote","ucwords","uppercase","lowercase","|","h1","h2","h3","h4","h5","h6","|","list-ul","list-ol","hr","|","link","image","code","code-block","table","datetime","html-entities","pagebreak","|","goto-line","clear","search","|","help","||", "watch", "fullscreen", "preview", "releaseIcon"];
            },

            /*自定义功能按钮*/
            toolbarIconTexts : {
                releaseIcon : "<span bgcolor=\"gray\">发布</span>",
                // index : "<span bgcolor=\"red\">返回首页</span>",
            },

            /*给自定义按钮指定回调函数*/
            toolbarHandlers:{
                releaseIcon : function(cm, icon, cursor, selection) {
                    contentCommit();//提交表单代码在下面
                },
                // index : function(){
                //     window.location.href = '返回首页的路径.html';
                // },
            }
        });

        /*
        // or
        testEditor = editormd({
            id      : "test-editormd",
            width   : "90%",
            height  : 640,
            path    : "../lib/"
        });
         */

        //读取剪切板
        $("#test-editormd").on('paste', function (ev) {
            var topicCode = $("#topicCode").val();
            //详细可查看clipboardData属性的使用方式
            var data = (ev.clipboardData || ev.originalEvent.clipboardData);
            var items1 = data.items;
            // console.log(items1);//输出 DataTransferItem对象
            var imageFile;
            for(var index in items1){
                var item = items1[index];
                //如果kind是file，可以用getAsFile()方法获取到文件
                if (item.kind === 'file') {
                    imageFile = item.getAsFile();
                    // console.log('获取到剪贴板的文件' + item.kind);
                    break;
                }else if(item.kind === 'string'){
                    // console.log('获取到剪贴板的字符串' + item.kind);
                }
            }

            //执行上传
            uploadTrigger(imageFile,topicCode);
        });


    });


    //执行上传
    function uploadTrigger(imageFile,topicCode){
        //topicCode为文章代码，需要在关联图片，从而实现预览时准确加载到图片
        var url = "api/onlineEdit/uploadFile?topicCode="+topicCode;
        var formdata = new FormData();
        formdata.append("file", imageFile);

        $.ajax({
            url: url,
            type: "post",
            data: formdata,
            //关闭序列化
            processData: false,
            contentType: false,
            success: function (data) {
                //data为后台返回的retMap数据
                if(data.retCode == "success"){
                    //向markdown区域插入该格式的值，从而实现图片在右侧显示
                    testEditor.insertValue("\n![" + data.file + "](" + data.rootPath + ")");
                } else {
                    console.log(data.msg);
                }
            },
            error : function(data){
            }
        });
    }

    /*提交表单的js*/
    function contentCommit(){
        var url = "api/onlineEdit/contentCommit"; //服务器路径
        $.ajax({
            type: "POST",
            url: url,
            headers:{'Accept': 'application/json, text/plain, */*',
                'Authorization' : '[[${token}]]' //存放token
            },
            data: {
                content : $('#content').val(),
                fileId  : "[[${fileId}]]"
            }, // serializes the form's elements.
            success: function(data)
            {
                zdconfirm("Markdown编辑","保存成功！");
            },
            error:function(e){
                zdconfirm("Markdown编辑","保存失败！");
            }
        });
    }
</script>
</body>
</html>